package com.tpl.core.basedata.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.tpl.core.basedata.dao.DeptDao;
import com.tpl.core.basedata.dao.RoleDao;
import com.tpl.core.basedata.dao.UserDao;
import com.tpl.core.basedata.dao.UserReRoleDao;
import com.tpl.core.basedata.service.DeptUserService;
import com.tpl.core.common.MD5;
import com.tpl.core.common.constant.IConstants;
import com.tpl.core.common.exception.RuleException;
import com.tpl.core.common.page.ListPage;
import com.tpl.core.common.page.Page;
import com.tpl.core.dao.ExecuteSql;
import com.tpl.core.entity.sys.Dept;
import com.tpl.core.entity.sys.Role;
import com.tpl.core.entity.sys.User;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;



/**
 * 说明 :
 * @author <a href="mailto:3380084@gmail.com">张坤雷</a>
 * @version 创建时间：2013-7-23 下午2:49:12 
 *
 */
public class DeptUserServiceImpl implements DeptUserService {
	private Log log=LogFactory.getLog(DeptUserServiceImpl.class);
	@Autowired
	private UserDao userDao;
	@Autowired
	private DeptDao deptDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserReRoleDao userReRoleDao;
	@Override
	
	public Page getUsersByDeptId2(Long deptId, User u, int pageIndex, int pageSize, Long tf) {
		if(tf==0){//不用查下级的情况
		int count=userDao.getUsersByDeptIdCount(deptId,u);
		if(count>0){
			List<User> list=userDao.getUserPageByDeptId(deptId,u, pageIndex, pageSize);
			return new ListPage(list, pageIndex, pageSize, count);
		}
		return new ListPage(new ArrayList(), count);
		}else{//需要查下级的情况
		int count=0;
		List<User> list=new ArrayList();
		List<Dept> listdept=deptDao.getDeptsByParentId(deptId);
		if(listdept.size()>0){  //有下级的情况
			
			
			for(int i=0;i<listdept.size();i++){//循环下级同时寻找下下级
				List<Dept> listdept2=deptDao.getDeptsByParentId(listdept.get(i).getId());
				if(listdept2.size()>0){
					for(int j=0;j<listdept2.size();j++){//循环这些部门
						int count2=userDao.getUsersByDeptIdCount(listdept2.get(j).getId(),u);
						if(count2>0){//如果有用户，则添加
							List<User> list2=userDao.getUserPageByDeptId(listdept2.get(j).getId(),u, pageIndex, pageSize);
							list.addAll(list2);
							count=count+count2;
					}
					
					}
				}
				int count1=userDao.getUsersByDeptIdCount(listdept.get(i).getId(),u);
				if(count1>0){//如果下级有部门则添加
					List<User> list1=userDao.getUserPageByDeptId(listdept.get(i).getId(),u, pageIndex, pageSize);
					list.addAll(list1);
					count=count+count1;
				}
			}
			int count2=userDao.getUsersByDeptIdCount(deptId,u);
			if(count2>0){//最后添加这个部门
				List<User> list2=userDao.getUserPageByDeptId(deptId,u, pageIndex, pageSize);
				list.addAll(list2);
			}
			return new ListPage(list, pageIndex, pageSize, count);
			

			
			
		}
		else
		{//需要查下级但是没有
			int count2=userDao.getUsersByDeptIdCount(deptId,u);
			if(count2>0){
				List<User> list2=userDao.getUserPageByDeptId(deptId,u, pageIndex, pageSize);
				list.addAll(list2);
			return new ListPage(list, pageIndex, pageSize, count);
			}
			return new ListPage(new ArrayList(), count);
		}
		
		
		}
		
		
			
		
		
		
		
		
	}
	
	@Override
	public User getUserById(Long id) {
		User user=userDao.getUserById(id);
//		user.setExpand(expandService.getExpand(ExpandEnum.USER, id));
		return user;
	}
	private String getDefultPwd(String userNo){
		String pwd="";
		switch(IConstants.DEFAULT_PWD_TYPE){
		case 1:
			pwd=IConstants.USER_DEFAULT_PWD;
			break;
		case 2:
			pwd=userNo.length()> IConstants.USER_DEFAULT_PWD_LAST_NUM?userNo.substring(userNo.length()-IConstants.USER_DEFAULT_PWD_LAST_NUM):userNo;
			break;
		}
		if(StringUtils.isEmpty(pwd))pwd="888888";
		String md5Pwd= MD5.getMD5Str(pwd);
		return md5Pwd;
	}
	@Override
	public void doSave(User user, Long deptId) {
		int count= ExecuteSql.getSingleResult(Integer.class,"select count(1) from SYS_USER where deleted=0 and id_card=? and id!=?",user.getIdCard(),user.getId()==null?0:user.getId());
		if(count>0){
			throw new RuleException("身份证重复，请重新输入！");
		}else{
			if(user.getId()!=null){
				userDao.updateUser(user);
			}else{
				String md5Pwd=getDefultPwd(user.getUserNo());
				user.setPassword(md5Pwd);
				user.setCreateDate(user.getUpdateDate());
				user.setCreator(user.getUpdator());
				userDao.insertUser(user); //插入用户，sys_user表
				ExecuteSql.execute("Insert Into Sys_Dept_Re_User(Dept_Id,User_Id,Default_Flag,State,User_Type)" +
						"values(?,?,1,1,1)", deptId,user.getId());//插入部门对应人员 表
				Role defaultRole = roleDao.getIsDefaultDeptRoleByDeptId(deptId);//获取该部门下的默认角色
				if(defaultRole!=null){
					if (defaultRole.getId()!=null) {
						userReRoleDao.insertUserReRole(user.getId(), defaultRole.getId());//插入人员对应角色
						Role role = new Role();
						role.setUserId(user.getId());
						role.setRoleId(defaultRole.getId());
						roleDao.insertRoleUser(role);
					}
				}else
					log.warn("Dept[id="+deptId+"] have not default role!");
		}
		
		}
//		expandService.doUpdateExpand(ExpandEnum.USER, user);
	}
	@Override
	public List<Dept> getUserDepts(Long userId) {
		List<Dept> list=deptDao.getUserDepts(userId);
		return list;
	}
	@Override
	public List<User> getUserByDeptId(Long deptId) {
		List<User> list = userDao.getUserByDeptId(deptId);
		return list;
	}
	@Override
	public void deleteUser(Long userId,Long deptId) { 
		if(userId==null||deptId==null)return;
		int flag=ExecuteSql.getSingleResult(Integer.class,"select 1 from sys_user where id=? and state=0", userId);
		if(flag>0){
			log.warn("用户被锁定,不能删除");
			return;//用户被锁定,不能删除
		}
		ExecuteSql.execute("delete from Sys_Dept_Re_User where USER_ID=? and DEPT_ID=?",userId,deptId);
		String rel=ExecuteSql.getSingleResult("select distinct 1 from Sys_Dept_Re_User where USER_ID=?", userId);
		if(StringUtils.isEmpty(rel))
			ExecuteSql.execute("update sys_user set deleted=1 where id=?", userId);
	}
	@Override
	public void deleteUsers(String userIds,Long deptId) {
		if(userIds==null||deptId==null)return;
		String[] ids=userIds.split(",");
		for(String userId : ids)
			deleteUser(Long.valueOf(userId), deptId);
	}
	@Override
	public List getCurDeptUsers(Long deptId,Long inDeptId) {
		List<User> list=userDao.getUserByDeptId(deptId, "not exists(select 1 from SYS_DEPT_RE_USER r where u.id=r.user_id and r.dept_id="+inDeptId+")");
		return  list;
	}
	@Override
	public void doSaveDistribution(Long deptId, Long[] userIds) throws Exception {
		Long roleId=ExecuteSql.getSingleResult(Long.class, "select r.ID from sys_role r where r.STATE=1 and r.DEPT_ID=? and deleted=0",deptId);
		for (int i = 0; i < userIds.length; i++) {
			Long userId=userIds[i];
			if(userId!=null){
				String sql="select 1 from SYS_DEPT_RE_USER dru where dru.user_id=? and dru.dept_id=?";
				String rel=ExecuteSql.getSingleResult(sql,userId,deptId);
				if(StringUtils.isEmpty(rel)){
					ExecuteSql.execute("Insert Into Sys_Dept_Re_User(Dept_Id,User_Id,Default_Flag,State,User_Type)" +
							"values(?,?,0,1,0)", deptId,userId);
					if(roleId>0){
						Role role = new Role();
						role.setUserId(userId);
						role.setRoleId(roleId);
						roleDao.insertRoleUser(role);
					}else
						log.warn("Dept[id="+deptId+"] have not default role!");
				}
			}
		}
		
	}
	@Override
	public void doSaveTranslation(Long inDeptId, Long outDeptId,Long userId) {
		Dept inDept=deptDao.getDeptById(inDeptId);
		Dept outDept=deptDao.getDeptById(outDeptId);
		/*//验证是否距离为1
		if(inDept.getParentId()!=outDept.getParentId()&&inDept.getParentId()!=outDept.getId()&&inDept.getId()!=outDept.getParentId()){
			throw new RuleException("人员无法跨2级调动");
		}
		//验证调出人员是否已经在调入部门
		String sql="select count(1) from sys_dept_re_user where dept_id=? and user_id=?";
		String rel=ExecuteSql.getSingleResult(sql,inDeptId,userId);
		if(Long.valueOf(rel)!=0){
			throw new RuleException("该人员已经存在于需调入的部门");
		}*/
		//调出原部门
		if(inDept.getParentId()==outDept.getParentId()||inDept.getParentId()==outDept.getId()){  //平级或降职调动，删除在原部门及子部门的权限
			ExecuteSql.execute("delete from SYS_DEPT_RE_USER where user_id=? and dept_id " +
					"in (select id from sys_dept where id=? or parent_id=?)",userId,outDeptId,outDeptId); //删除和原部门及子部门的关系
			
			ExecuteSql.execute("delete from SYS_USER_RE_ROLE where user_id=? and role_id " +
					"in (select id from sys_role where dept_id=? or dept_id " +
					"in (select id from sys_dept where parent_Id=?))",userId,outDeptId,outDeptId);     //删除人员在调出部门及子部门的角色
		}
		if(inDept.getId()==outDept.getParentId()){
			ExecuteSql.execute("delete from SYS_DEPT_RE_USER where user_id=? and dept_id " +
					"in (select id from sys_dept where id=? or parent_id=?)",userId,outDeptId,outDeptId); //对升职不删原来的bug的修改
			
			ExecuteSql.execute("delete from SYS_USER_RE_ROLE where user_id=? and role_id " +
					"in (select id from sys_role where dept_id=? or dept_id " +
					"in (select id from sys_dept where parent_Id=?))",userId,outDeptId,outDeptId);     //
	
		}
		
		//调入到新部门，升职调动只将人员调入上级部门
		ExecuteSql.execute("Insert Into Sys_Dept_Re_User(Id,Dept_Id,User_Id,Default_Flag,State,User_Type)" +
				"values(null,?,?,0,1,1)", inDeptId,userId);
		//调入新部门后 默认角色为普通用户
		String str=ExecuteSql.getSingleResult("select id from sys_role where dept_id=? and state=1",inDeptId);
		int roleId=0;
		if(!StringUtils.isEmpty(str))
		roleId= Integer.valueOf(str);
		ExecuteSql.execute("Insert into sys_user_re_role(ID,user_Id,role_Id ) values(null,?,?)", userId,roleId);
	}
	@Override
	public boolean isRootUser(Long userId,Long currDeptId) {
		String sql="select count(1) from sys_dept_re_user where dept_id=? and user_id=?";
		String rel=ExecuteSql.getSingleResult(sql,currDeptId,userId);
		if(Long.valueOf(rel)!=0){
			return true;
		}
			return false;
	}

	@Override
	public List<Dept> getTransferDepts(Long rootDeptId,Long userId) {
		return deptDao.getTransferDepts(rootDeptId,userId);
	}
	@Override
	public void doChangePwd(User user) {
		ExecuteSql.execute("update Sys_User set password=? where id=?", getDefultPwd(user.getUserNo()),user.getId());
		
	}

	@Override
	public void doImportUser(List<User> list, Long deptId) {
		for(User user : list)
			doSave(user, deptId);
	}

	@Override
	public void doChangeState(Long userId, Integer state) {
		ExecuteSql.execute("update Sys_User set state=? where id=?",state,userId);
	}

	@Override
	public Page getUserByDeptIds(String deptIds,int pageIndex, int pageSize) {
		int count=userDao.getUserByDeptIdsCount(deptIds);
		List<User> list=null; 
		if(count>0){
			list= userDao.getUserByDeptIds(deptIds,pageIndex,pageSize);
			return new ListPage(list, pageIndex, pageSize, count);
		}
		return new ListPage(new ArrayList<>(),count);
	}

	@Override
	public List<User> getUserListByDeptId(Long deptId) {
		return userDao.getUserByDeptId(deptId);
	}

	@Override
	public Page getUsersByDeptId(Long deptId, User u, int pageIndex, int pageSize) {
		int count=userDao.getUsersByDeptIdCount(deptId,u);
		if(count>0){
			List<User> list=userDao.getUserPageByDeptId(deptId,u, pageIndex, pageSize);
			//for(User us:list){
			//	us.setExpand(expandService.getExpand(ExpandEnum.USER, us.getId()));
			//}
			return new ListPage(list, pageIndex, pageSize, count);
		}
		return new ListPage(new ArrayList(), count);
	}
}
